const app = getApp()

Page({
  data: {
    avatarUrl: '/img/logo.png',
    nickname: '未授权',
    openid: ''
  },

  onLoad() {
    var that = this;
    if(wx.getStorageSync('userinfo').avatar == null){
      that.setData({
        avatarUrl:'/img/logo.png'
      })
    }else{
      that.setData({
        avatarUrl:wx.getStorageSync('userinfo').avatar
      })
    }
    if(wx.getStorageSync('userinfo').nickname == null){
      that.setData({
        nickname:'未授权'
      })
    }else{
      that.setData({
        nickname:wx.getStorageSync('userinfo').nickname
      })
    }
    this.setData({
      openid:wx.getStorageSync('openid')
    })
  },

  onChooseAvatar(e) {
    var that = this;
    const { avatarUrl } = e.detail 
    that.setData({
      avatarUrl,
    })
    wx.uploadFile({
      url: app.globalData.domain + 'index/uploadImages',
      filePath: that.data.avatarUrl,
      name: 'file',
      success: function(r) {
        that.setData({
          avatarUrl: r.data
        });
      }
    })
  },

  getNickname(e) {
    this.setData({
      nickname : e.detail.value
    })
  },

  submit_result(e) {
    const that = this;
    if(that.data.avatarUrl == "/img/logo.png"){
      wx.showToast({
        title: '请选择头像',
        icon: 'none',
        duration: 2000,
      })
    }else if(that.data.nickname == "未授权"){
      wx.showToast({
        title: '请选择/输入昵称',
        icon: 'none',
        duration: 2000,
      })
    }else{
      wx.request({
        url: app.globalData.domain + 'index/updateUserInfo/',
        method: "POST",
        data: {
          nickname: that.data.nickname,
          avatar: that.data.avatarUrl,
          openid: that.data.openid
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (e) {
          wx.setStorageSync("userinfo", e.data.data.userinfo);
          that.setData({
            avatarUrl:wx.getStorageSync('userinfo').avatar,
            nickname:wx.getStorageSync('userinfo').nickname,
            openid:wx.getStorageSync('userinfo').openid
          })
          wx.showToast({
            title: '更新成功！',
            icon: 'none',
            duration: 1000,
          })
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/center/index',
            })
          }, 1000);
        }
      })
    }
  }
})
